<template>
  <div class="product-analysis">
    <!-- 页面标题和日期筛选 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">产品销售分析</h1>
        <div class="date-filter">
          <a-range-picker
            v-model="dateRange"
            format="YYYY-MM-DD"
            :placeholder="['开始日期', '结束日期']"
            @change="onDateRangeChange"
            :allowClear="true"
            style="width: 240px; margin-right: 12px"
          />
          <a-button type="primary" @click="refreshData" :loading="loading">
            <a-icon type="reload" />
            刷新数据
          </a-button>
        </div>
      </div>
    </div>

    <!-- 概览统计卡片 -->
    <div class="overview-section">
      <div class="overview-grid">
        <div class="overview-card">
          <div class="card-content">
            <div class="card-header">
              <span class="card-title">总销售额</span>
              <a-tooltip title="统计期间内所有产品的销售总金额">
                <a-icon type="question-circle" class="help-icon" />
              </a-tooltip>
            </div>
            <div class="card-value">{{ formatCurrency(overview.totalSales) }}</div>
            <div class="card-trend" :class="getTrendClass(overview.salesGrowthRate)">
              <a-icon :type="getTrendIcon(overview.salesGrowthRate)" />
              {{ overview.salesGrowthRate }}%
              <span class="trend-label">较去年同期</span>
            </div>
          </div>
        </div>

        <div class="overview-card">
          <div class="card-content">
            <div class="card-header">
              <span class="card-title">总订单数</span>
              <a-tooltip title="统计期间内的订单总数量">
                <a-icon type="question-circle" class="help-icon" />
              </a-tooltip>
            </div>
            <div class="card-value">{{ formatNumber(overview.totalOrders) }}</div>
            <div class="card-trend" :class="getTrendClass(overview.ordersGrowthRate)">
              <a-icon :type="getTrendIcon(overview.ordersGrowthRate)" />
              {{ overview.ordersGrowthRate }}%
              <span class="trend-label">较去年同期</span>
            </div>
          </div>
        </div>

        <div class="overview-card">
          <div class="card-content">
            <div class="card-header">
              <span class="card-title">产品总数</span>
              <a-tooltip title="统计期间内销售的产品总数量">
                <a-icon type="question-circle" class="help-icon" />
              </a-tooltip>
            </div>
            <div class="card-value">{{ formatNumber(overview.totalProducts) }}</div>
            <div class="card-trend" :class="getTrendClass(overview.productsGrowthRate)">
              <a-icon :type="getTrendIcon(overview.productsGrowthRate)" />
              {{ overview.productsGrowthRate }}%
              <span class="trend-label">较去年同期</span>
            </div>
          </div>
        </div>

        <div class="overview-card">
          <div class="card-content">
            <div class="card-header">
              <span class="card-title">平均订单金额</span>
              <a-tooltip title="统计期间内订单的平均金额">
                <a-icon type="question-circle" class="help-icon" />
              </a-tooltip>
            </div>
            <div class="card-value">{{ formatCurrency(overview.avgOrderAmount) }}</div>
            <div class="card-trend" :class="getTrendClass(overview.avgAmountGrowthRate)">
              <a-icon :type="getTrendIcon(overview.avgAmountGrowthRate)" />
              {{ overview.avgAmountGrowthRate }}%
              <span class="trend-label">较去年同期</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 分析图表区域 -->
    <div class="charts-section">
      <div class="charts-grid">
        <!-- 产品系列销售排行 -->
        <div class="chart-card">
          <div class="chart-header">
            <h3 class="chart-title">产品系列销售排行</h3>
            <a-tooltip title="按销售金额排序的产品系列TOP10">
              <a-icon type="question-circle" class="help-icon" />
            </a-tooltip>
          </div>
          <div class="chart-content">
            <div ref="seriesChart" class="chart-container"></div>
          </div>
        </div>

        <!-- 产品颜色分析 -->
        <div class="chart-card">
          <div class="chart-header">
            <h3 class="chart-title">产品颜色分析</h3>
            <a-tooltip title="不同颜色产品的销售分布情况">
              <a-icon type="question-circle" class="help-icon" />
            </a-tooltip>
          </div>
          <div class="chart-content">
            <div ref="colorChart" class="chart-container"></div>
          </div>
        </div>
      </div>

    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import {
  getProductOverview,
  getProductSeriesRanking,
  getProductColorAnalysis,
} from '@/api/oms/statistics'
import moment from 'moment'

export default {
  name: 'ProductAnalysis',
  data() {
    return {
      loading: false,
      dateRange: [],
      resizeTimer: null,
      overview: {
        totalSales: 0,
        totalOrders: 0,
        totalProducts: 0,
        avgOrderAmount: 0,
        salesGrowthRate: 0,
        ordersGrowthRate: 0,
        productsGrowthRate: 0,
        avgAmountGrowthRate: 0,
      },
      seriesData: [],
      colorData: [],
      charts: {},
    }
  },
  mounted() {
    this.initDateRange()
    this.loadData()
    this.initCharts()
    window.addEventListener('resize', this.handleResize)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize)
    Object.values(this.charts).forEach((chart) => {
      if (chart) {
        chart.dispose()
      }
    })
  },
  methods: {
    initDateRange() {
      // 默认显示最近30天的数据
      const endDate = moment()
      const startDate = moment().subtract(30, 'days')
      this.dateRange = [startDate, endDate]
    },

    onDateChange(dates) {
      this.dateRange = dates
      if (dates && dates.length === 2) {
        this.loadData()
      }
    },

    refreshData() {
      this.loadData()
    },

    async loadData() {
      this.loading = true
      try {
        const startDate = this.dateRange[0] ? this.dateRange[0].format('YYYY-MM-DD') : null
        const endDate = this.dateRange[1] ? this.dateRange[1].format('YYYY-MM-DD') : null

        // 并行加载所有数据
        const [overviewRes, seriesRes, colorRes] = await Promise.all([
          getProductOverview(startDate, endDate),
          getProductSeriesRanking(startDate, endDate, 10),
          getProductColorAnalysis(startDate, endDate),
        ])

        this.overview = overviewRes.result || this.overview
        this.seriesData = seriesRes.result || []
        this.colorData = colorRes.result || []

        this.updateCharts()
      } catch (error) {
        console.error('加载数据失败:', error)
        this.$message.error('加载数据失败，请稍后重试')
      } finally {
        this.loading = false
      }
    },

    initCharts() {
      this.$nextTick(() => {
        this.charts.seriesChart = echarts.init(this.$refs.seriesChart)
        this.charts.colorChart = echarts.init(this.$refs.colorChart)
      })
    },

    updateCharts() {
      this.updateSeriesChart()
      this.updateColorChart()
    },

    updateSeriesChart() {
      if (!this.charts.seriesChart) return

      const option = {
        title: {
          text: '产品系列销售排行',
          left: 'center',
          textStyle: {
            fontSize: window.innerWidth < 768 ? 14 : 16,
            fontWeight: 'normal',
          },
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'shadow' },
          formatter: (params) => {
            const data = params[0]
            return `${data.name}<br/>销售额: ¥${this.formatNumber(data.value)}<br/>市场份额: ${data.data.marketShare}%`
          },
        },
        grid: {
          left: window.innerWidth < 768 ? '10%' : '3%',
          right: '4%',
          bottom: window.innerWidth < 768 ? '15%' : '3%',
          containLabel: true,
        },
        xAxis: {
          type: 'category',
          data: this.seriesData.map((item) => item.seriesName),
          axisLabel: {
            rotate: window.innerWidth < 768 ? 45 : 0,
            fontSize: window.innerWidth < 480 ? 10 : 12,
          },
        },
        yAxis: {
          type: 'value',
          name: '销售额(元)',
          axisLabel: {
            formatter: (value) => `¥${this.formatNumber(value)}`,
            fontSize: window.innerWidth < 480 ? 10 : 12,
          },
        },
        series: [
          {
            type: 'bar',
            data: this.seriesData.map((item) => ({
              value: item.totalSales,
              marketShare: item.marketShare,
            })),
            itemStyle: { color: '#3B82F6' },
          },
        ],
      }

      this.charts.seriesChart.setOption(option)
    },

    updateColorChart() {
      if (!this.charts.colorChart) return

      // 如果没有数据，显示占位数据
      const chartData = this.colorData.length > 0 ? this.colorData.map((item) => ({
        value: item.totalQuantity || item.quantity || 0,
        name: item.colorName || '未知颜色',
      })) : [
        { value: 100, name: '白色' },
        { value: 80, name: '黑色' },
        { value: 60, name: '灰色' },
        { value: 40, name: '棕色' },
        { value: 20, name: '其他' }
      ]

      const option = {
        title: {
          text: '产品颜色分析',
          left: 'center',
          textStyle: {
            fontSize: window.innerWidth < 768 ? 14 : 16,
            fontWeight: 'normal',
          },
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)',
        },
        legend: {
          orient: window.innerWidth < 768 ? 'horizontal' : 'vertical',
          left: window.innerWidth < 768 ? 'center' : 'left',
          bottom: window.innerWidth < 768 ? 0 : 'auto',
          textStyle: {
            fontSize: window.innerWidth < 480 ? 10 : 12,
          },
        },
        series: [
          {
            name: '颜色销量',
            type: 'pie',
            radius: window.innerWidth < 768 ? '40%' : '50%',
            center: window.innerWidth < 768 ? ['50%', '40%'] : ['50%', '50%'],
            data: chartData,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)',
              },
            },
          },
        ],
      }

      this.charts.colorChart.setOption(option)
    },

    handleResize() {
      // 延迟执行resize，避免频繁调用
      if (this.resizeTimer) {
        clearTimeout(this.resizeTimer)
      }
      this.resizeTimer = setTimeout(() => {
        Object.values(this.charts).forEach((chart) => {
          if (chart) {
            chart.resize()
          }
        })
      }, 100)
    },

    formatCurrency(value) {
      if (!value) return '¥0'
      return `¥${this.formatNumber(value)}`
    },

    formatNumber(value) {
      if (!value) return '0'
      return Number(value).toLocaleString()
    },

    getTrendClass(rate) {
      const numRate = Number(rate)
      if (numRate > 0) return 'trend-up'
      if (numRate < 0) return 'trend-down'
      return 'trend-flat'
    },

    getTrendIcon(rate) {
      const numRate = Number(rate)
      if (numRate > 0) return 'arrow-up'
      if (numRate < 0) return 'arrow-down'
      return 'minus'
    },

    onDateRangeChange(dates) {
      this.dateRange = dates
      if (dates && dates.length === 2) {
        this.loadData()
      }
    },
  },
}
</script>

<style lang="less" scoped>
.product-analysis {
  background: #f5f7fa;
  min-height: 100vh;
  padding: 24px;
  max-width: 1400px;
  margin: 0 auto;

  // 响应式容器宽度
  @media (max-width: 1440px) {
    max-width: 1200px;
  }

  @media (max-width: 1200px) {
    max-width: 100%;
    padding: 16px;
  }

  @media (max-width: 768px) {
    padding: 12px;
  }
}

.page-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 16px;
  padding: 24px 32px;
  margin-bottom: 24px;
  box-shadow: 0 8px 32px rgba(102, 126, 234, 0.15);

  .header-content {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .page-title {
      font-size: 28px;
      font-weight: 600;
      color: #ffffff;
      margin: 0;
      text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }

    .date-filter {
      display: flex;
      align-items: center;
      gap: 12px;

      .ant-btn-primary {
        background: rgba(255, 255, 255, 0.2);
        border: 1px solid rgba(255, 255, 255, 0.3);
        border-radius: 8px;
        font-weight: 500;
        backdrop-filter: blur(10px);
        transition: all 0.3s ease;

        &:hover {
          background: rgba(255, 255, 255, 0.3);
          border-color: rgba(255, 255, 255, 0.5);
          transform: translateY(-1px);
        }
      }

      .ant-calendar-picker {
        .ant-calendar-picker-input {
          background: rgba(255, 255, 255, 0.9);
          border: 1px solid rgba(255, 255, 255, 0.3);
          border-radius: 8px;
          backdrop-filter: blur(10px);

          &:hover {
            border-color: rgba(255, 255, 255, 0.5);
          }
        }
      }
    }
  }
}

.overview-section {
  margin-bottom: 24px;

  .overview-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 16px;

    // 响应式网格布局
    @media (max-width: 1400px) {
      grid-template-columns: repeat(4, 1fr);
      gap: 14px;
    }

    @media (max-width: 1200px) {
      grid-template-columns: repeat(2, 1fr);
      gap: 16px;
    }

    @media (max-width: 768px) {
      grid-template-columns: 1fr;
      gap: 12px;
    }

    @media (max-width: 480px) {
      gap: 8px;
    }
  }

  .overview-card {
    background: white;
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease;
    min-height: 140px;

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
    }

    .card-content {
      padding: 24px;
      height: 100%;
      display: flex;
      flex-direction: column;
      justify-content: space-between;

      @media (max-width: 768px) {
        padding: 20px;
      }

      @media (max-width: 480px) {
        padding: 16px;
      }

      .card-header {
        display: flex;
        align-items: center;
        margin-bottom: 16px;

        .card-title {
          font-size: 14px;
          color: #909399;
          font-weight: 500;

          @media (max-width: 480px) {
            font-size: 13px;
          }
        }

        .help-icon {
          margin-left: 8px;
          color: #c0c4cc;
          cursor: help;

          @media (max-width: 480px) {
            margin-left: 4px;
          }
        }
      }

      .card-value {
        font-size: 24px;
        font-weight: 600;
        color: #303133;
        margin-bottom: 12px;
        word-break: break-all;

        @media (max-width: 768px) {
          font-size: 22px;
        }

        @media (max-width: 480px) {
          font-size: 20px;
        }
      }

      .card-trend {
        font-size: 12px;
        display: flex;
        align-items: center;
        flex-wrap: wrap;

        @media (max-width: 480px) {
          font-size: 11px;
        }

        .trend-label {
          margin-left: 4px;
          color: #909399;

          @media (max-width: 480px) {
            margin-left: 2px;
          }
        }

        &.trend-up {
          color: #67c23a;
        }

        &.trend-down {
          color: #f56c6c;
        }

        &.trend-flat {
          color: #909399;
        }
      }
    }
  }
}

.charts-section {
  .charts-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 16px;
    margin-bottom: 16px;

    // 响应式图表网格
    @media (max-width: 1200px) {
      gap: 14px;
    }

    @media (max-width: 768px) {
      grid-template-columns: 1fr;
      gap: 12px;
    }

    @media (max-width: 480px) {
      gap: 8px;
    }
  }

  .chart-card {
    background: white;
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    overflow: hidden;

    .chart-header {
      display: flex;
      align-items: center;
      padding: 20px 24px 0;

      @media (max-width: 768px) {
        padding: 16px 20px 0;
      }

      @media (max-width: 480px) {
        padding: 12px 16px 0;
      }

      .chart-title {
        margin: 0;
        font-size: 16px;
        font-weight: 600;
        color: #303133;

        @media (max-width: 768px) {
          font-size: 15px;
        }

        @media (max-width: 480px) {
          font-size: 14px;
        }
      }

      .help-icon {
        margin-left: 8px;
        color: #c0c4cc;
        cursor: help;

        @media (max-width: 480px) {
          margin-left: 4px;
        }
      }
    }

    .chart-content {
      padding: 16px 24px 24px;

      @media (max-width: 768px) {
        padding: 12px 20px 20px;
      }

      @media (max-width: 480px) {
        padding: 8px 16px 16px;
      }

      .chart-container {
        width: 100%;
        height: 300px;

        // 响应式图表高度
        @media (max-width: 1200px) {
          height: 280px;
        }

        @media (max-width: 768px) {
          height: 260px;
        }

        @media (max-width: 480px) {
          height: 240px;
        }

        // 确保图表在容器内正确显示
        > div {
          width: 100% !important;
          height: 100% !important;
        }
      }
    }
  }

  // 趋势图表单独占一行，更大的显示空间
  .trend-chart-card {
    grid-column: 1 / -1;

    .chart-container {
      height: 350px;

      @media (max-width: 1200px) {
        height: 320px;
      }

      @media (max-width: 768px) {
        height: 280px;
      }

      @media (max-width: 480px) {
        height: 240px;
      }
    }
  }
}
</style>
